package com.lanswon.icc.common.security.config;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.lanswon.icc.common.core.constant.ResultConstant;
import com.lanswon.icc.common.core.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 */
@Component
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
//        if (isAjaxRequest(request)) {
            response.setStatus(HttpStatus.OK.value());
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setContentType( MediaType.APPLICATION_JSON_UTF8_VALUE);
            PrintWriter printWriter = response.getWriter();
            Result result = new Result(ResultConstant.EX_UNAUTHORIZED, "您当前无权限访问!");
            printWriter.write(JSONObject.toJSONString(result));
            printWriter.flush();
//
//        } else {
//            response.sendRedirect("/login");
//        }

    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}